<template>
  <ElDialog v-model="visible" scroll :max-height="600" centered width="220mm" title="打印预览">
    <div ref="print" id="print" class="print-container" v-loading="loading">
      <header>餐谱（{{ recipeDetail.recipeName }}）</header>
      <div class="info-section">
        <div class="info-item">
          <span class="info-label">航空公司：</span>
          <span class="info-value">{{ recipeDetail.airlineName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">航线类型：</span>
          <span class="info-value">{{ recipeDetail.airlineTypeName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">舱位等级：</span>
          <span class="info-value">{{ recipeDetail.cabinClassName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">套餐：</span>
          <span class="info-value">{{ recipeDetail.mealSetName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">餐食类别：</span>
          <span class="info-value">{{ recipeDetail.mealServiceName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">餐谱编号：</span>
          <span class="info-value">{{ recipeDetail.recipeCode }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">有效时间：</span>
          <span class="info-value">{{ recipeDetail.validTime }}</span>
        </div>
      </div>

      <div class="table-section">
        <table class="print-table">
          <thead>
            <tr>
              <th class="num">序号</th>
              <th class="name">菜品名称</th>
              <th class="tableware">餐具</th>
              <th class="ratio">配餐比例（%）</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in recipeDetail.recipeDetailRespVOs" :key="item.id">
              <td class="text-center num">{{ index + 1 }}</td>
              <td class="text-left name">{{ item.mealName || '-' }}</td>
              <td class="text-left tableware">{{ item.tablewareName || '-' }}</td>
              <td class="text-center ratio">{{ item.ratio || '0' }}</td>
            </tr>
            <!-- 空数据处理 -->
            <tr
              v-if="
                !recipeDetail.recipeDetailRespVOs || recipeDetail.recipeDetailRespVOs.length === 0
              "
            >
              <td colspan="4" class="text-center">暂无数据</td>
            </tr>
          </tbody>
        </table>
        <div class="footer-section">
          <div class="footer-item">
            <span class="footer-label">打印人：</span>
            <span class="footer-value">{{ user.nickname || '' }}</span>
          </div>
          <div class="footer-item">
            <span class="footer-label">打印时间：</span>
            <span class="footer-value">{{ new Date().toLocaleString() }}</span>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button @click="handlePrint" type="primary" :disabled="loading">打印</el-button>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { TablewareVO } from '@/api/acm/acmtableware'
import { RecipeApi } from '@/api/pplan/recipe'
import { RecipeMealApi, RecipeMealVO } from '@/api/pplan/recipemeal'
import { TablewareApi } from '@/api/pplan/tableware'
import { getStrDictOptions } from '@/utils/dict'
import printJS from 'print-js'
import { formatToDateTime } from '@/utils/dateUtil'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'RecipePrint' })
const props = defineProps<{
  recipeId?: number
}>()

const recipeDetail = ref<any>({})
const loading = ref(true)
const visible = ref(false)
const print = ref<HTMLElement | null>(null)

const recipeMealAllList = ref<RecipeMealVO[]>([]) // 完整菜品列表
const tablewareAllList = ref<TablewareVO[]>([]) // 完整餐具列表

const user = useUserStore().getUser

/** 加载完整的菜品列表（仅加载一次） */
const loadAllRecipeMeals = async () => {
  if (recipeMealAllList.value.length > 0) return recipeMealAllList.value
  try {
    const data = await RecipeMealApi.getRecipeMealSimpleList('')
    recipeMealAllList.value = data // 存储全部菜品数据
    return data
  } catch (error) {
    console.error('加载菜品列表失败:', error)
    return []
  }
}

/** 加载完整的餐具列表（仅加载一次） */
const loadAllTablewares = async () => {
  if (tablewareAllList.value.length > 0) return tablewareAllList.value
  try {
    const data = await TablewareApi.getTablewareSimpleList('')
    tablewareAllList.value = data // 存储全部餐具数据
    return data
  } catch (error) {
    console.error('加载餐具列表失败:', error)
    return []
  }
}

/** 格式化有效时间 */
const formatValidTime = (startTime?: string, endTime?: string) => {
  if (!startTime && !endTime) return '无'
  if (startTime && endTime) {
    return `${formatToDateTime(startTime, 'YYYY-MM-DD')} 至 ${formatToDateTime(endTime, 'YYYY-MM-DD')}`
  }
  return startTime
    ? formatToDateTime(startTime, 'YYYY-MM-DD')
    : formatToDateTime(endTime!, 'YYYY-MM-DD')
}

// 预加载数据
loadAllRecipeMeals()
loadAllTablewares()

watch(
  () => props.recipeId,
  async (newId) => {
    if (!newId) return
    try {
      loading.value = true
      // 确保基础数据已加载完成
      await Promise.all([loadAllRecipeMeals(), loadAllTablewares()])

      const response = await RecipeApi.getRecipe(newId)
      response.validTime = formatValidTime(response.startDate, response.endDate)
      const airCompanys = getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_ID)
      recipeDetail.value = response
      recipeDetail.value.airlineName =
        airCompanys.find((item) => item.value === recipeDetail.value.airlineId)?.label || ''
      const airTypes = getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_TYPE)
      recipeDetail.value.airlineTypeName =
        airTypes.find((item) => item.value === recipeDetail.value.airlineType)?.label || ''
      const airlineClass = getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_CLASS)
      recipeDetail.value.cabinClassName =
        airlineClass.find((item) => item.value === recipeDetail.value.cabinClass)?.label || ''
      const mealServices = getStrDictOptions(DICT_TYPE.PPLAN_MEAL_SERVICE)
      recipeDetail.value.mealServiceName =
        mealServices.find((item) => item.value === recipeDetail.value.mealService)?.label || ''
      const mealSets = getStrDictOptions(DICT_TYPE.PPLAN_MEAL_SET)
      recipeDetail.value.mealSetName =
        mealSets.find((item) => item.value === recipeDetail.value.mealSet)?.label || ''

      // 处理菜品详情数据
      recipeDetail.value.recipeDetailRespVOs = (response.recipeDetailRespVOs || []).map(
        (elem: any) => {
          return {
            ...elem,
            mealName:
              recipeMealAllList.value.find((fElem) => fElem.id == elem.receipeMealId)?.mealName ||
              '',
            tablewareName:
              tablewareAllList.value.find((tElem) => tElem.id == elem.tablewareId)?.name || ''
          }
        }
      )
    } catch (error) {
      console.error('获取餐谱详情失败:', error)
    } finally {
      loading.value = false
    }
  },
  { immediate: true }
)

const open = () => {
  visible.value = true
}

const handlePrint = () => {
  // 优化打印配置，确保内容在241mm*139mm纸张上居中显示，表格内容不溢出
  printJS({
    printable: 'print',
    type: 'html',
    targetStyles: ['*'],
    ignoreElements: [],
    scanStyles: true,
    showModal: false,
    modalMessage: '正在准备打印...',
    font_size: '11pt',
  //   style: `
  //   @page { size: 241mm 139mm; margin: 10mm; }  /* 调整为针式打印机纸张规格 */
  //   body { margin: 0; padding: 0; }
  //   #print { 
  //     margin: 0 auto;
  //     max-width: 241mm;  /* 调整为纸张宽度 */
  //     text-align: center;
  //   }
  //   .print-container > * { 
  //     text-align: left;
  //     margin-left: auto;
  //     margin-right: auto;
  //   }
  //   .print-table { 
  //     margin: 0 auto;
  //     width: 210mm;
  //     table-layout: fixed; /* 固定表格布局，防止溢出 */
  //   }
  //   .print-table th, .print-table td {
  //     word-break: break-all; /* 强制换行 */
  //     white-space: normal; /* 允许内容换行 */
  //   }
  // `
  })
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
@media print {
  @page {
    margin: 10mm; /* 减小边距以适应纸张 */
  //  size: 241mm 139mm; /* 调整为针式打印机纸张规格 */

    /* 确保页面边距一致 */
  }

  body {
    padding: 0;
    margin: 0;
    font-family: "Times New Roman", Times, serif;
  }

  .print-container {
    // width: 100% !important;
    width: 220mm !important; /* 调整为纸张宽度 */
    margin: 0 auto !important;
    font-family: "Times New Roman", Times, serif;
    font-size: 12px;
    box-sizing: border-box !important;;
  }

  header {
    width: 100%;
    margin: 0 auto;
    border-bottom: 1px solid #000;
  }

  .info-section {
    width: 100%;
    margin: 0 auto;
    border-bottom: 1px solid #000;
  }

  .print-table {
    width: 100% !important;
    margin: 0 auto !important;
    border: 1px solid #000 !important;
    box-sizing: border-box !important;
    table-layout: fixed !important; /* 固定表格布局 */
  }

  .print-table th,
  .print-table td {
    padding: 4px 6px !important; /* 减小内边距 */
    font-weight: normal !important;
    word-break: break-all !important;
    white-space: normal !important;
    border: 1px solid #000 !important;
    box-sizing: border-box !important;
  }

  /* 打印时的表格列宽控制 */
  .print-table .num {
    width: 8% !important;
  }

  .print-table .name {
    width: 42% !important;
  }

  .print-table .tableware {
    width: 30% !important;
  }

  .print-table .ratio {
    width: 20% !important;
  }

  .footer-section {
    width: 100%;
    margin: 0 auto;
  }
}

/* 标题样式 */
header {
  width: 100%;
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-size: 20px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

/* 信息区域样式 */
.info-section {
  display: flex;
  width: 100%;
  padding-bottom: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  // width: 33%;
  width: 65mm; /* 根据241mm纸张调整，每行3个 */
  margin-bottom: 10px;
  align-items: center;
}

.info-label {
  width: 6em;
  // margin-right: 8px;
  // font-weight: bold;
  white-space: nowrap;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  word-break: normal;
  white-space: nowrap;
}

.table-section {
  width: 90%;
}


.print-table {
  width: 100%;
  max-width: 100%;
  word-wrap: break-word; /* 允许单词换行 */

  /* 针对针式打印机的优化 */
  border: 1px solid #ddd;
  border-collapse: collapse;
  table-layout: fixed; /* 固定表格布局，防止内容溢出 */

  .num {
    width: 8%; /* 缩小序号列宽度 */
  }

  .name {
    width: 42%; /* 调整菜品名称列宽度 */
  }

  .tableware {
    width: 30%; /* 调整餐具列宽度 */
  }

  .ratio {
    width: 20%; /* 保持配餐比例列宽度 */
  }
}

.print-table th,
.print-table td {
  max-width: 0; /* 配合break-all使用，确保内容不会溢出 */
  padding: 6px 8px; /* 减小内边距，节省空间 */
  font-weight: normal;
  text-align: center;
  word-break: break-all; /* 强制换行，避免内容溢出 */
  white-space: normal; /* 允许内容自动换行 */
  border: 1px solid #ddd;
}

.print-table td.text-left {
  text-align: left; /* 保持文本左对齐 */
}

/* 尾部信息样式 */
.footer-section {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding-top: 10px;
}

.footer-item {
  display: flex;
  align-items: center;
}

.footer-label {
  margin-right: 10px;
  white-space: nowrap;
}

.footer-value {
  flex: 1;
  white-space: nowrap;
}

/* 文本对齐样式 */
.text-center {
  text-align: center !important;
}

.text-left {
  text-align: left !important;
}

.text-right {
  text-align: right !important;
}

/* 打印容器样式 */
.print-container {
  width: 100%;
  padding: 10px;
  margin: 0 auto;
  box-sizing: border-box;
}
</style>
